<template>
  <div id="Login">
    <van-nav-bar title="黑马头条 - 登录" fixed />
    <van-form @submit="login">
      <van-field
        v-model="form.mobile"
        name="tel"
        label="手机号码"
        placeholder="请输入手机号码"
        required
        :rules="rules.mobile"
      />
      <van-field
        v-model="form.code"
        type="password"
        name="登录密码"
        label="登录密码"
        placeholder="请输入登录号码"
        required
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex';
import { loginAPI } from '../api/userAPI';

export default {
  // name 是当前组件的名称（建议为每个组件都指定唯一的 name 名称）
  name: 'Login',
  data() {
    return {
      form: {
        mobile: '13888888123',
        code: '246810',
      },
      rules: {
        // 手机号的校验规则
        mobile: [
          { required: true, message: '请填写您的手机号', trigger: 'onBlur' },
          {
            pattern: /^1\d{10}$/,
            message: '请填写正确的手机号',
            trigger: 'onBlur',
          },
        ],
        // 密码的校验规则
        code: [
          { required: true, message: '请填写您的密码', trigger: 'onBlur' },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(['upDataTokenInfo']),
    async login() {
      const { data: res } = await loginAPI(this.form);
      if (res.message === 'OK') {
        this.upDataTokenInfo(res.data);
        const navPath = this.$route.query.pre || '/'
        this.$router.replace(navPath)
      }
    },
  },
};
</script>

<style lang="less" scoped>
#Login {
  padding-top: 46px;
}
</style>
